class Request {
  constructor(baseURL = "") {
    this.baseURL = import.meta.env.VITE_API_BASE_URL || "/api";
  }

  // 请求拦截器
  setRequestInterceptors(request) {
    // 可扩展添加token等逻辑
    return request;
  }

  // 响应拦截器
  setResponseInterceptors(response) {
    if (!response.ok) {
      return response.json().then((err) => {
        throw new Error(err.message || "Request failed");
      });
    }
    return response.json();
  }

  async request({ url, method = "GET", data = null }) {
    const options = {
      method,
      headers: {
        "Content-Type": "application/json",
      },
    };

    if (data) {
      options.body = JSON.stringify(data);
    }

    try {
      const baseurl = `${this.baseURL}${url}`;
      const response = await fetch(baseurl, options);
      return this.setResponseInterceptors(response);
    } catch (error) {
      console.error("Request error:", error);
      throw error;
    }
  }

  get(url, params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request({
      url: query ? `${url}?${query}` : url,
      method: "GET",
    });
  }

  post(url, data) {
    return this.request({ url, method: "POST", data });
  }

  // 可扩展其他方法...
}

// 创建实例（建议在这里配置baseURL）
export const request = new Request("/api");
